package com.example.androidshixi;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;

public class CartActivity extends AppCompatActivity {

    private ListView cartListView;
    private TextView totalPriceTextView;
    private ArrayAdapter<Product> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        cartListView = findViewById(R.id.cart_list_view);
        totalPriceTextView = findViewById(R.id.total_price_text_view);
        TextView checkoutButton = findViewById(R.id.checkout_button);

        // 获取购物车中的商品列表
        List<Product> cartItems = ShoppingCart.getInstance().getCartItems();

        // 设置适配器
        adapter = new ArrayAdapter<Product>(this, R.layout.cart_item, R.id.cart_product_name_text_view, cartItems) {
            @Override
            public View getView(int position, View convertView, android.view.ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                Product product = cartItems.get(position);
                ((ImageView) view.findViewById(R.id.cart_product_image_view)).setImageResource(product.getImageResId());
                ((TextView) view.findViewById(R.id.cart_product_name_text_view)).setText(product.getName());
                ((TextView) view.findViewById(R.id.cart_product_price_text_view)).setText("￥" + product.getPrice());
                ImageView deleteButton = view.findViewById(R.id.cart_delete_button);
                deleteButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ShoppingCart.getInstance().removeItem(product);
                        adapter.notifyDataSetChanged();
                        updateTotalPrice();
                    }
                });
                return view;
            }
        };
        cartListView.setAdapter(adapter);

        // 处理结算按钮点击事件
        checkoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 实现结算逻辑
            }
        });

        updateTotalPrice();
    }

    private void updateTotalPrice() {
        double totalPrice = ShoppingCart.getInstance().getTotalPrice();
        totalPriceTextView.setText("总价: ￥" + totalPrice);
    }
}